package com.woniu113.junk.commons.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Data
@Component//该注解将该类变成组件,才能进行依赖注入
public class AliyunOSSUtil {
    private String host="oss-cn-chengdu.aliyuncs.com";//节点域名,aliyun服务器地址
    private String accessId="LTAI5tA1CnR8wWbpZ7xdiQtD";//账号的身份ID
    private String accessSecret="dBbV6trY1v6DRKHAxvodOWMoFhItAM";//账号的身份凭证(密钥)

    /**
     * 上传文件
     * @param file 文件数据
     * @param name 文件名
     * @param bucketName 存储空间名
     * @return 文件的访问地址
     */
    public String uploadFile(InputStream file, String name, String bucketName) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //上传
            ossClient.putObject(bucketName, name, file);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return "https://" + bucketName + "."+ host + "/"+name;
    }

    /**
     * 删除文件
     * @param bucketName 存储空间名
     * @param name 文件名
     * @return
     */
    public boolean deleteFile(String bucketName,String name) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, name);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return true;
    }
}
